import { MessageBox } from "element-ui";
import axios from "axios";

// toolbar工具栏的工具选项（默认展示全部）
const toolOptions = [
  ["bold", "italic", "underline", "strike"],
  ["blockquote", "code-block"],
  [{ header: 1 }, { header: 2 }],
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }],
  [{ indent: "-1" }, { indent: "+1" }],
  [{ direction: "rtl" }],
  [{ size: ["small", false, "large", "huge"] }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ color: [] }, { background: [] }],
  [{ font: [] }],
  [{ align: [] }],
  ["clean"],
  ["link", "image", "video"]
];
const handlers = {
  image: function image() {
    var self = this;
    var fileInput = this.container.querySelector("input.ql-image[type=file]");
    if (fileInput === null) {
      fileInput = document.createElement("input");
      fileInput.setAttribute("type", "file");
      fileInput.setAttribute("name", "img");
      fileInput.setAttribute(
        "accept",
        "image/png, image/gif, image/jpeg, image/bmp, image/x-icon"
      );
      fileInput.classList.add("ql-image");
      // 监听选择文件
      fileInput.addEventListener("change", function() {
        let formData = new FormData();
        formData.append("file", fileInput.files[0]);
        axios({
          method: "post",
					url: '/saveImageFile',
          headers: {
            "Content-Type": "multipart/form-data"
          },
          withCredentials: true,
          data: formData,
          dataType: "json"
        }).then(res => {
          fileInput.value = "";
          if (res.data.topCont.remark == "操作成功!") {
            let length = self.quill.getSelection(true).index;
            self.quill.insertEmbed(length, "image", res.data.svcCont.data);
            self.quill.setSelection(length + 1);
          } else {
            MessageBox.alert("图片插入失败，文件上传异常", "警告！！！", {
              confirmButtonText: "确定"
            });
          }
        });
      });
      this.container.appendChild(fileInput);
    }
    fileInput.click();
  }
};

export default {
  placeholder: "",
  theme: "snow", // 主题
  modules: {
    toolbar: {
      container: toolOptions, // 工具栏选项
      handlers: handlers // 事件重写
    }
  }
};
